<template>
	<view class="bg-light flex flex-column" :style="'padding-bottom:' + fixedHeight + 'px'">
		<!-- 选项 -->
		<view class="flex mx-3 mt-2">
			<view @click="handlecount(0)" class="rounded-top-left-lg flex justify-center w-100 py-1"
				:class="count == 0 ? 'bg-info' : 'bg-white'">
				<text class="font font-weight-bold" :class="count == 0 ? 'text-white' : 'text-info'">配送地址</text>
			</view>
			<view @click="handlecount(1)" class="rounded-top-right-lg flex justify-center w-100 py-1"
				:class="count == 1 ? 'bg-info' : 'bg-white' " style="border-radius: 0 14rpx 0 0">
				<text class="font" :class="count == 1 ? 'text-white' : 'text-info'">用户自提</text>
			</view>
		</view>
		<!-- 收货地址 -->
		<view v-if="count == 0" class="">
			<view v-if="Address == null" @click="onAddress()"
				class="bg-white mx-3 mb-4 px-2 py-3 rounded-bottom-lg flex align-center">
				<text class="ml-2 font font-weight-bold w-100">请选择收货地址</text>
				<uni-icons class="mx-2 flex-shrink" type="right" size="20"></uni-icons>
			</view>
			<view v-else @click="onAddress()" class="bg-white mx-3 mb-2 p-3 rounded-bottom-lg">
				<view class="flex align-center">
					<!-- <uni-icons class="mx-2 flex-shrink" type="info" size="20"></uni-icons> -->
					<image :src="Domain_ICON + '/position.png'" class="rounded-circle bg-info"
						style="width: 30rpx; height: 30rpx" mode=""></image>
					<text class="font ml-1">{{ Address.Name }}</text>
					<text class="font ml-1">{{ Address.Phone }}</text>
				</view>
				<view class="pl-4">
					<text class="font-sm">配送地址：{{ Address.Address }}</text>
				</view>
			</view>
		</view>
		<!-- 自提 -->
		<view v-if="count == 1">
			<view v-if="Pickup == null" @click="onPickupPerson()"
				class="bg-white mx-3 mb-4 px-2 py-3 rounded-bottom-lg flex align-center" style="position: relative">
				<text class="font-sm">请选择提货人</text>
				<text class="font" style="position: absolute; right: 20rpx">&gt;</text>
			</view>
			<view v-else class="mx-3 mb-4  bg-white rounded-bottom-lg text-dark">
				<!-- 已选择提货人 -->
				<view class="ml-2 py-2 flex justify-between align-center">
					<view class="flex flex-column w-100">
						<text class="font font-weight-bold">{{PickupAddress?PickupAddress.Enterprise_Name:'世纪华联超市'}}</text>
						<text class="font-sm my-2">{{PickupAddress?PickupAddress.Enterprise_Address + PickupAddress.Enterprise_Name:'黑龙江省绥化市海伦市学府路和美家园东北侧世纪华联超市'}}</text>
						<view @click="onPickupPerson()" class="mt-2 flex justify-between">
							<text class="font">提货人</text>
							<view>
								<text class="font font-weight-bold">{{ Pickup.Name }} {{ Pickup.Phone }}</text>
								<uni-icons type="right" class="mr-2" color="#828d96" size="16"></uni-icons>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 商品种类 -->
		<view class="bg-white mx-4 mb-4 px-2 py-3 rounded-lg" v-for="(item, index) in SalesOrder" :key="index">
			<view class="flex" style="position: relative">
				<image class="rounded-lg flex-shrink" style="width: 150rpx; height: 150rpx"
					:src="Domain_IMG + item.Picture_URL" mode=""></image>
				<view class="ml-2 pr-10 text-ellipsis" style="width: 100%; position: relative">
					<text class="font">{{ item.Article_Name }}</text><br />
					<text class="font-sm text-muted">规格:{{ item.Specifications_Name }}</text>
					<text class="font-sm"
						style="position: absolute; bottom: 0; left: 0">￥{{ Price(item.Sales_Unit_Price) }}</text>
				</view>
				<text class="font-sm" style="position: absolute;right: 0;height: 100%; line-height: 150rpx;">×{{ item.quantity }}</text>
			</view>
			<view class="py-2">
				<text class="font-sm text-muted" style="display: inline-block">产品注意事项</text>
				<text class="font-sm" style="display: inline-block; float: right">严格品质 退货无忧 &gt;</text>
			</view>
			<view class="bg-light p-3 rounded-lg flex align-center">
				<text class="font flex-shrink">订单留言：</text>
				<textarea v-model="item.message" class="font" placeholder-class="text-muted" style="width: 100%"
					placeholder="请输入你的订单备注信息" auto-height></textarea>
			</view>
		</view>
		<!-- 商品金额 -->
		<view class="mx-4 rounded-lg p-3 bg-white">
			<text class="font text-muted">商品金额：</text>
			<text class="font" style="display: inline-block; float: right">￥{{ Price(Amount) }}</text>
		</view>
		<!-- 支持配送 -->
		<view v-if="ispay && !count">
			<!-- 配送金额 -->
			<view class="mx-4 flex justify-between align-center mt-2 rounded-lg p-3 bg-white">
				<view class="font text-muted">配送金额：<text class="font-small">(当商品金额到达￥{{ Sales_Amount }}时可免配送费)</text></view>
				<text class="font" style="display: inline-block; float: right">￥{{ Price(DeliveryAmount) }}</text>
			</view>
			<!-- 配送距离 -->
			<view class="mx-4 mt-2 rounded-lg p-3 bg-white">
				<text class="font text-muted">当前地址配送距离约：</text>
				<text class="font" style="display: inline-block; float: right">{{ distance }}km</text>
			</view>
		</view>
		<!-- 不支持配送 -->
		<view v-else-if="!ispay && !count" class="mx-4 mt-2 rounded-lg py-2 flex align-center border border-hover-warning"  >
			<uni-icons class="mx-2" type="info" color="#ffc107" size="20"></uni-icons>
			<text class="font-sm text-warning" >当前地址暂时无法配送，可更换地址，或{{PickupAddress?"自提点自提！":"到店自提！"}}</text>
		</view>
		<!-- 底层总计 -->
		<view id="fixed" class="fixed-bottom py-1 bg-white">
			<view class="m-auto flex align-center justify-between" style="width: 90%">
				<view class="" style="width: 100%">
					<text class="font">共{{ Quantity }}件 合计</text><text
						class="font-md font-weight-bold">￥{{ accAdd(Amount, count ? 0 : DeliveryAmount) }}</text>
				</view>
				<view @click="submit()" v-if="ispay || count"
					class="flex-shrink text-white bg-info py-3 text-center rounded-lg" hover-class="bg-hover-info"
					:hover-stay-time="150" style="width: 35%">
					<text class="font">提交订单</text>
				</view>
				<view v-else class="flex-shrink text-white bg-danger py-3 text-center rounded-lg"
					hover-class="bg-hover-info" :hover-stay-time="150" style="width: 35%">
					<text class="font-sm">该地区暂时无法配送</text>
				</view>
			</view>
		</view>
<!-- 		<showPaynew :amount="accAdd(Amount, count ? 0 : DeliveryAmount)" :sales_order="sales_order"
			:Article_Name="Article_Name" :show="isShow" @Close="handleClose()"></showPaynew> -->
		<showPaynew2 :amount="accAdd(Amount, count ? 0 : DeliveryAmount)" :sales_order="sales_order"
			:Article_Name="Article_Name" :show="isShow" @Close="handleClose()"></showPaynew2>
		<showPaysnew :amount="accAdd(Amount, count ? 0 : DeliveryAmount)" :sales_orders="sales_orders"
			:Article_Name="Article_Name" :show="isShow2" @Close="handleClose()"></showPaysnew>
		<!-- 用户协议 -->
		<view class="mask" v-if="mask">
			<view class="model_box">
				<view class="mb-tit">用户协议和隐私政策</view>
				<view class="mb-content">
					<view class="mb-con">尊敬的用户您好！</view>
					<view class="mb-con">请您务必认真阅读、充分理解“用户服务协议”和“隐私政策”各条款，包括但不限于为了向您提供数据、分享、统计等服务所要获取的权限信息。</view>
					<view class="mb-con1">
						<navigator class="mb-a" url="/pages/my/privacyPolicy">《用户服务协议》</navigator>
						和
						<navigator class="mb-a" url="/pages/my/privacyPolicy">《隐私政策》</navigator>
					</view>
					<text>请您仔细阅读上方的的用户协议与隐私政策，请点击同意接受我们的服务</text>
				</view>
				<view class="checkbox">
					<view class="qr">
						<navigator class="noUse" target="miniProgram" open-type="exit">暂不使用</navigator>
						<view class="agree" @click="agree">同意</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import showPaynew from "@/components/payment/paynew.vue";
	import showPaynew2 from "@/components/payment/paynew2.vue";
	import showPaysnew from "@/components/payment/paysnew.vue";
	import { NowTime } from "@/static/js/DateUtil.js";
	import { accMul,accAdd } from "@/static/js/GeneralUtil.js";
	import { getReceivingAction } from '@/api/global.js'
	export default {
		components: {
			showPaynew,
			showPaynew2,
			showPaysnew,
		},
		data() {
			return {
				count: 0, //自提或个人信息
				Domain_IMG: app.globalData.Domain_IMG, //全局变量--域名
				isShow: false, //调起支付方式
				isShow2: false, //调起支付方式
				ispay: true,
				payway: true, //选取支付方式
				fixedHeight: 0, //底部悬浮栏高度
				Address: null, //默认地址
				Pickup:null,//默认提货人
				PickupAddress:null,//提货地址
				SalesOrder: [], //销售价格单--接收
				mask: false, //协议
				Amount: 0,
				DeliveryAmount: 0,
				Sales_Amount: 0,
				distance: 0,
				Quantity: 0,
				Article_Name: [],
				sales_orders: [],
				sales_order: {
					Sales_Order_SerialNumber: "",
					Store_SerialNumber: "",
					Sales_Date: NowTime(),
					Open_ID: app.globalData.openid,
					Sales_Amount: "",
					Sales_Contacts: "",
					Sales_Phone: "",
					Sales_Address: "",
					Sales_Message: "",
					Collection_Amount: 0,
					Delivery_Amount: 0,
					Sales_ID: "xiaoshou1",
					Receive_Type: 0,
					Refund_Type: 0,
					App_ID: app.globalData.appid,
					Enterprise_Info_SerialNumber: app.globalData.enterprise,
					Children: {
						sales_order_detail: [{
							Sales_Order_Detail_SerialNumber: "",
							Sales_Order_SerialNumber: "",
							Sales_Unit_Price_Stock_SerialNumber: "",
							Article_SerialNumber: "",
							Sign: "无货货主",
							Quantity: "",
							Unit_Price: "",
							Sales_Unit_Price: "",
							Amount: "",
							Receive_Type: 0,
							Refund_Type: 0,
							Enterprise_Info_SerialNumber: app.globalData.enterprise,
							Article_Specifications_SerialNumber: "",
						}, ],
					},
				},
				Domain_ICON: app.globalData.Domain_ICON, //全局变量域名
			};
		},
		onShow() {
			//检查有无自提点
			this.getReceiving(()=>{
				if (uni.getStorageSync("AddressData")) {
					//本地存储地址
					this.Address = uni.getStorageSync("AddressData");
					this.Getdistance(uni.getStorageSync("Store_SerialNumber"));
					if (this.count == 0) {
						this.sales_order.Sales_Address = this.Address.Address.replaceAll(" ", "/");
					} else {
						this.sales_order.Sales_Address = "用户自提";
						
					}
					this.sales_order.Sales_Contacts = this.Address.Name;
					this.sales_order.Sales_Phone = this.Address.Phone;
					if (this.payway) {
						this.sales_orders.forEach((item) => {
							item.Sales_Address = this.Address.Address.replaceAll(" ", "/");
							item.Sales_Contacts = this.Address.Name;
							item.Sales_Phone = this.Address.Phone;
						});
					}
				}
			})
			if(uni.getStorageSync("PickupData")){
				this.Pickup = uni.getStorageSync("PickupData");
			}
			if (uni.getStorageSync("mask")) {//协议
				//本地存储地址
				this.mask = false;
			} else {
				this.mask = true;
			}
		},
		onLoad(options) {
			console.log(options);
			this.fixed();
			if (options.key == undefined) {
				this.payway = false;
				this.SalesOrder = JSON.parse(decodeURIComponent(options.SalesOrder));
				this.SalesOrder.forEach((item) => {
					this.Article_Name.push(item.Article_Name);
					item.message = "";
					this.sales_order.Sales_Date = NowTime();
					this.sales_order.Children.sales_order_detail[0].Amount =
						this.sales_order.Children.sales_order_detail[0].Amount +
						accMul(item.Sales_Unit_Price, item.quantity);
					this.sales_order.Children.sales_order_detail[0].Quantity =
						this.sales_order.Children.sales_order_detail[0].Quantity +
						parseInt(item.quantity);
					this.sales_order.Store_SerialNumber = item.Store_SerialNumber;
					this.sales_order.Sales_Amount = accMul(
						item.Sales_Unit_Price,
						item.quantity
					);
					this.Amount = this.sales_order.Children.sales_order_detail[0].Amount;
					this.Quantity =
						this.sales_order.Children.sales_order_detail[0].Quantity;
					this.sales_order.Children.sales_order_detail[0] = {
						Sales_Order_Detail_SerialNumber: "",
						Sales_Order_SerialNumber: "",
						Sign:item.Sign,
						Sales_Unit_Price_Stock_SerialNumber: item.Sales_Unit_Price_Stock_SerialNumber,
						Article_SerialNumber: item.Article_SerialNumber,
						Quantity: parseInt(item.quantity),
						Unit_Price: item.Unit_Price,
						Sales_Unit_Price: item.Sales_Unit_Price,
						Amount: accMul(item.Sales_Unit_Price, item.quantity),
						Receive_Type: 0,
						Refund_Type: 0,
						Enterprise_Info_SerialNumber: app.globalData.enterprise,
						Article_Specifications_SerialNumber: item.Article_Specifications_SerialNumber,
					};
				});
			} else {
				this.payway = true;
				this.SalesOrder = JSON.parse(decodeURIComponent(options.SalesOrder));
				this.SalesOrder.forEach((item) => {
					this.Article_Name.push(item.Article_Name);
					item.message = "";
					item.quantity = item.Quantity;
					this.Amount = accAdd(this.Amount, item.Amount);
					this.Quantity = this.Quantity + parseInt(item.Quantity);
					this.sales_order.Store_SerialNumber = item.Store_SerialNumber;
					this.sales_order.Sales_Amount = accMul(
						item.Sales_Unit_Price,
						item.quantity
					);
					this.sales_orders.push({
						Sales_Order_SerialNumber: item.Sales_Order_SerialNumber,
						Sales_Date: NowTime(),
						Sales_Unit_Price: item.Sales_Unit_Price,
						Store_SerialNumber: item.Store_SerialNumber,
						Amount: item.Amount,
						Quantity: item.Quantity,
						Sales_Unit_Price_Stock_SerialNumber: item.Sales_Unit_Price_Stock_SerialNumber,
					});
				});
			}
			//是否可以自提
			
		},
		computed: {
			Price() {
				//补零
				return function(price) {
					if (price) {
						if (RegExp(/\./).exec(price)) {
							return price;
						} else {
							return price + ".00";
						}
					} else {
						return "";
					}
				};
			},
		},
		methods: {
			async getReceiving(callback){
				//有无自提点
				let Object_location = uni.getStorageSync("location")
				if(Object_location){//有
					const res = await getReceivingAction({Address:Object_location.data.town,Open_ID:app.globalData.openid})
					console.log(res);
					if(res.Data.length==1){
						this.PickupAddress = res.Data[0]
					}
					callback();
				}else{//没有
					callback();
				}
			},
			fixed() {
				//底部模块高度获取
				uni
					.createSelectorQuery()
					.select("#fixed")
					.boundingClientRect((res) => {
						this.fixedHeight = res.height + this.rpxToPx(20);
					})
					.exec();
			},
			handlecount(i) {
				this.count = i;
				if (uni.getStorageSync("AddressData")) {
					if (i == 0) {
						this.sales_order.Sales_Address = this.Address.Address.replace(" ","/").replace(" ", "/").replace(" ", "/");
						this.sales_order.Delivery_Amount = this.DeliveryAmount;
						this.sales_order.Sales_Type = '0'
					} else {
						if(this.PickupAddress){
							this.sales_order.Sales_Address = this.PickupAddress.Enterprise_Address + this.PickupAddress.Enterprise_Name;
							this.sales_order.Sales_Type = '1'
							this.sales_order.Delivery_Amount = 0;
						}
					}
				}
			},
			Getdistance(Store_SerialNumber) {//判断配送距离
				uni.request({
					//查询所选地址与发货点的距离
					header: {
						"Content-Type": "application/x-www-form-urlencoded",
					},
					url: app.globalData.Domain_Name + "/WeChatAddressDistance", //销售价格单
					method: "POST",
					data: {
						latitude: this.Address.latitude,
						longitude: this.Address.longitude,
						Store_SerialNumber,
						Open_ID: app.globalData.openid,
					},
					success: ({data}) => {
						// 1.先检查是否能配送
						let str = this.PickupAddress?"自提点自提！":"到店自提！"
						if (data.Data.length == 0 && data.EXIST) {
							//  否，判断有无自提点， 有--> 提示弹窗，可前往自提点自提
							//                       没有--> 提示弹窗， 提示可到店自提
							//当前位置是否存在自提点
							uni.showModal({
								title: "提示",
								content: "当前地址无法进行配送服务，可更换地址或选择" + str,
								cancelText:"取消",
								confirmText:"选择自提",
								success:(res)=> {
									if (res.confirm) {
										this.handlecount(1)		
									}
								},
							});
							this.DeliveryAmount = 0;
							this.Sales_Amount = 0;
							this.distance = "";
							this.ispay = false;
						} else if (data.Data.length == 1 && data.EXIST) {
							//  是，能配送  提示配送费 ，弹窗，自提或配送费
							uni.showModal({
								title: "提示",
								content: "当前地址可进行配送或选择"+str,
								cancelText:"取消",
								confirmText:"选择自提",
								success:(res)=> {
									if (res.confirm) {
										this.handlecount(1)		
									}
								},
							});
							this.ispay = true;
							this.DeliveryAmount = data.Data[0].Delivery_Amount;
							this.Sales_Amount = data.Data[0].Sales_Amount;
							this.distance = Number(data.Data[0].distance).toFixed(2);
							this.sales_order.Delivery_Amount = this.DeliveryAmount;
						}
					},
				});
			},
			agree() {
				//协议确认
				this.mask = false;
				uni.setStorageSync("mask", true);
				app.globalData.Rights_Type = "1";
			},
			
			submit() {
				//调起支付方式
				if (this.Address != null) {
					if (this.payway) {
						this.isShow2 = true;
						this.sales_orders.forEach((item, index) => {
							item.Sales_Message = this.SalesOrder[index].message;
							item.Delivery_Amount = this.count ? 0 : this.DeliveryAmount;
						});

						console.log(this.sales_orders);
					} else {
						this.isShow = true;
						this.sales_order.Sales_Message = this.SalesOrder[0].message;
					}
				} else {
					uni.showToast({
						title: "请选择地址",
						icon: "error",
					});
				}
			},
			handleClose() {
				//关闭支付关闭
				if (this.payway) {
					this.isShow2 = false;
				} else {
					this.isShow = false;
				}
			},
			tags() {
				uni.showModal({
					title: "系统提示",
					content: "根据您选择送货的地址不同,配送费可能会发生变化(点击我已知晓后续将不再提示该提示)",
					confirmText: "我已知晓",
					success(res) {
						if (res.confirm) {
							uni.setStorageSync("tags", "1");
							uni.navigateTo({
								url: "/pages/my/address?Path=/pages/index/submitOrderOld",
							});
						}
					},
				});
			},
			onAddress() {
				//跳转到地址列表
				if (uni.getStorageSync("tags") == "" ? true : false) {
					this.tags();
				} else {
					uni.navigateTo({
						url: "/pages/my/address?Path=/pages/index/submitOrderOld",
					});
				}
			},
			onPickupPerson(){
				//跳转到提货人列表
				uni.navigateTo({
					url: "/pages/my/pickupPerson?Path=/pages/index/submitOrderOld",
				});
			},
			rpxToPx(rpx) {
				//rpx转px
				const screenWidth = uni.getSystemInfoSync().screenWidth;
				return (screenWidth * Number.parseInt(rpx)) / 750;
			},
			accAdd(arg1, arg2) {
				//浮点型相加
				var r1, r2, m;
				try {
					r1 = arg1.toString().split(".")[1].length;
				} catch (e) {
					r1 = 0;
				}
				try {
					r2 = arg2.toString().split(".")[1].length;
				} catch (e) {
					r2 = 0;
				}
				m = Math.pow(10, Math.max(r1, r2));
				return (arg1 * m + arg2 * m) / m;
			},
		},
	};
</script>

<style lang="scss">
	page {
		background-color: #f8f9fa;
	}

	.mask {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 999;

		.model_box {
			width: 80%;
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			// z-index: 1000;
			background: #fff;
			// height:48%;
			border-radius: 15rpx;
		}

		.mb-content {
			padding: 10rpx 20rpx 10rpx 25rpx;
			box-sizing: border-box;
			height: 80%;
			overflow: scroll;
		}

		.mb-tit {
			padding: 15rpx 0rpx;
			box-sizing: border-box;
			font-size: 34rpx;
			text-align: center;
		}

		.mb-con {
			font-size: 30rpx;
			text-indent: 2rem;
			line-height: 1.5;
		}

		.mb-con1 {
			font-size: 30rpx;
			text-indent: 2rem;
			display: flex;

			.mb-a {
				// width: 180rpx;
				height: 40rpx;
				display: inline-block;
				padding: 0;
				margin: 0;
				color: #006df7;
				text-decoration: underline;
				text-indent: 0rem;
			}
		}

		.checkbox {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 11%;
		}

		.checkbox .qx {
			width: 50%;
			text-align: center;
			border-right: 1rpx solid #efefef;
		}

		.qr {
			position: relative;
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			box-szing: border-box;
			font-size: 30rpx;
			padding: 0;
			padding-right: 30rpx;

			.noUse {
				width: 50%;
				text-align: center;
				border-right: 1rpx solid #f3f3f3;
				color: #bbbbbb;
				padding-bottom: 15rpx;
			}

			.agree {
				width: 50%;
				text-align: center;
				font-size: 30rpx;
				color: #006df7;
				padding-bottom: 15rpx;
			}
		}
	}
</style>